package com.dm.webCrawler.common.utils.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 通用http工具封装
 * 
 * @author ruoyi
 */
public class HttpHelper
{
    private static final Logger LOGGER = LoggerFactory.getLogger(HttpHelper.class);

    public static String getBodyString(ServletRequest request)
    {
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = null;
        try (InputStream inputStream = request.getInputStream())
        {
            reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
            String line = "";
            while ((line = reader.readLine()) != null)
            {
                sb.append(line);
            }
        }
        catch (IOException e)
        {
            LOGGER.warn("getBodyString出现问题！");
        }
        finally
        {
            if (reader != null)
            {
                try
                {
                    reader.close();
                }
                catch (IOException e)
                {
                    LOGGER.error("",e);
                }
            }
        }
        return sb.toString();
    }

    /**
     * 将复制谷歌调试工具中复制的header转换成map
     * @param headerStr
     * @return
     */
    public static Map<String,String> convertHeaderMap(String headerStr){
        String[] lines = headerStr.split("\n");
        Map<String,String> re=new HashMap<>();
        if(lines.length>0){

            for (String line : lines) {
                if(line.startsWith(":")){
                    int index = line.indexOf(":",1);
                    re.put(line.substring(0,index).trim(),line.substring(index+1,line.length()).trim());
                }else{
                    int index = line.indexOf(":");
                    re.put(line.substring(0,index).trim(),line.substring(index+1,line.length()).trim());
                }
            }
            
        }
        return re;
    }

    /**
     * urlget请求参数解析
     * @param actionData
     * @return
     */
    public static  Map<String,String> getParamMaps(String actionData) {
        Map<String,String> paramsMap=new HashMap<>();
        String[] params = actionData.split("&");
        for (String param : params) {
            String[] paramArr = param.split("=");
            if(paramArr.length>=2){
                paramsMap.put(paramArr[0],paramArr[1]);
            }

        }
        return paramsMap;
    }
}
